package com.corpgovernment.organization.util;

import lombok.extern.slf4j.Slf4j;

import java.util.StringJoiner;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author dlz
 * @since 2023/8/11
 */
@Slf4j
public class LogUtil {

    /**
     * 尝试执行某个方法并记录日志
     * 
     * @param execFunc 要执行的方法
     * @param <R> 返回值类型
     * @return 执行结果
     */
    public static <R> R tryAndLog(Function<StringJoiner, R> execFunc) {
        StringJoiner sj = new StringJoiner(System.lineSeparator());
        Exception e = null;
        try {
            return execFunc.apply(sj);
        } catch (Exception ex) {
            e = ex;
            throw ex;
        } finally {
            if (e != null) {
                log.error(sj.toString(), e);
            } else {
                log.info(sj.toString());
            }
        }
    }

    /**
     * 尝试执行某个方法并记录日志
     * 
     * @param execFunc 要执行的方法
     */
    public static void tryExecAndLog(Consumer<StringJoiner> execFunc) {
        StringJoiner sj = new StringJoiner(System.lineSeparator());
        Exception e = null;
        try {
            execFunc.accept(sj);
        } catch (Exception ex) {
            e = ex;
            throw ex;
        } finally {
            if (e != null) {
                log.error(sj.toString(), e);
            } else {
                log.info(sj.toString());
            }
        }
    }
}
